//
//  PAImageAsynManager.m
//  PAMobileWallet
//
//  Created by Gavin Zhang on 7/25/13.
//  Copyright (c) 2013 平安付. All rights reserved.
//

#import "PAImageAsynManager.h"
#import "PAImageRequest.h"
#import "ASIHTTPRequest.h"

static PAImageAsynManager *_sharedInstance;


@implementation PAImageAsynManager
@synthesize imgCacheMap         = _imgCacheMap;
#pragma mark - singleton
+ (PAImageAsynManager *)sharedInstance
{
    if (!_sharedInstance) {
        _sharedInstance = [[super allocWithZone:NULL] init];
    }
    return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
    return [PAImageAsynManager sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)init
{
    self = [super init];
    if (self) {
        BOOL isExist = NO;
        BOOL isDirectory = NO;
        NSString * docPath = DocumentsPath;
        NSString * imgsDir = [docPath stringByAppendingPathComponent:ImgCacheDir];
        isExist = [[NSFileManager defaultManager] fileExistsAtPath:imgsDir isDirectory:&isDirectory];
        if (!(isExist && isDirectory)) {
            NSError * error = nil;
            BOOL isCreated = [[NSFileManager defaultManager] createDirectoryAtPath:imgsDir
                                                       withIntermediateDirectories:NO
                                                                        attributes:nil
                                                                             error:&error];
            if (!isCreated) {
                NSLog(@"创建头像缓存目录失败");
            }
        }
        NSString *mapPath = [imgsDir stringByAppendingPathComponent:@"imgMap.plist"];
        isExist = [[NSFileManager defaultManager] fileExistsAtPath:mapPath];
        if (isExist) {
            self.imgCacheMap = [[NSMutableDictionary alloc] initWithContentsOfFile:mapPath];
        }else{
            self.imgCacheMap = [[NSMutableDictionary alloc] initWithCapacity:0];
        }
    }
    return self;
}
#pragma mark -
- (void)loadImgWithRequest:(PAImageRequest *)req
{
    NSString *tempDigest = [self.imgCacheMap objectForKey:req.key];
    if ([tempDigest isEqualToString:req.digest]) {
        /*
         *  头像未更新，直接使用缓存数据
         *  无需再次下载
         */
        if (req.paImageAsynDelegate && [req.paImageAsynDelegate respondsToSelector:@selector(paImageRequestSuccess:)]) {
            NSString *docPath = DocumentsPath;
            NSString *imgFilePath = [[docPath  stringByAppendingPathComponent:ImgCacheDir] stringByAppendingPathComponent:req.key];
            NSData *imgData = [NSData dataWithContentsOfFile:imgFilePath];
            if (imgData) {
                [req.paImageAsynDelegate paImageRequestSuccess:imgData];
            }
        }
        
    }else{
        /*
         *  头像
         */
        req.delegate = self;
        req.bufferData = [NSMutableData data];
        [req startAsynchronous];
    }
    

}

#pragma mark - ASIHTTPRequestDelegate implementation
- (void)requestStarted:(ASIHTTPRequest *)request
{
    if ([request isKindOfClass:[PAImageRequest class]]){
        PAImageRequest *req = (PAImageRequest *)request;
        if (req.paImageAsynDelegate && [req.paImageAsynDelegate respondsToSelector:@selector(paImageRequestStarted)]) {
            [req.paImageAsynDelegate paImageRequestStarted];
        }
    }
    
}
//- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
//{}
//- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL
//{}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    if ([request isKindOfClass:[PAImageRequest class]]) {
        PAImageRequest *req = (PAImageRequest *)request;
        if (req.paImageAsynDelegate && [req.paImageAsynDelegate respondsToSelector:@selector(paImageRequestSuccess:)]) {
            [req.paImageAsynDelegate paImageRequestSuccess:req.bufferData];
            if (req.key && ![req.key isEqualToString:@""]) {
                NSString *docPath = DocumentsPath;
                NSString *imgCacheDir = [docPath  stringByAppendingPathComponent:ImgCacheDir];
                NSString *imgFilePath = [imgCacheDir stringByAppendingPathComponent:req.key];
                if ([req.bufferData writeToFile:imgFilePath atomically:YES]) {
                    NSLog(@"缓存头像成功");
                    [self.imgCacheMap setObject:req.digest forKey:req.key];
                    [self.imgCacheMap writeToFile:[imgCacheDir stringByAppendingPathComponent:@"imgMap.plist"] atomically:YES];
                }else{
                    NSLog(@"缓存头像失败");
                }
            }else{
                NSLog(@"没有电话时候不做头像缓存");
            }
        }
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"image requestFailed\n%@",request.error);
    if ([request isKindOfClass:[PAImageRequest class]]) {
        PAImageRequest *req = (PAImageRequest *)request;
        if (req.paImageAsynDelegate && [req.paImageAsynDelegate respondsToSelector:@selector(paImageRequestFailed)]) {
            [req.paImageAsynDelegate paImageRequestFailed];
        }
    }
}
//- (void)requestRedirected:(ASIHTTPRequest *)request
//{}
- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
{
    if ([request isKindOfClass:[PAImageRequest class]]) {
        PAImageRequest *req = (PAImageRequest *)request;
        [req.bufferData appendData:data];
    }
}
//- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request
//{}
//- (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request
//{}

@end
